package com.toulezu.test.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

@Service
public class RegisterService {

    @Autowired
    private UserService userService;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int register() {

        try {
          return userService.addUser();
        } catch (Exception e) {
        }

        return -1;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public int registerCycle() {

        try {
            return userService.addUser();
        } catch (Exception e) {
        }

        return -1;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public int batchRegister() {

        CompletableFuture completableFuture1 = CompletableFuture.supplyAsync(() -> userService.addUser());
        CompletableFuture completableFuture2 = CompletableFuture.supplyAsync(() -> userService.addUser());
        CompletableFuture completableFuture3 = CompletableFuture.supplyAsync(() -> userService.addUser());

        try {
            CompletableFuture.allOf(new CompletableFuture[]{completableFuture1, completableFuture2, completableFuture3}).get();
        } catch (Exception e) {
        }

        return 1;
    }
}
